module.exports=app=>{
  const express = require('express')
  const jwt = require('jsonwebtoken')
  //const assert = require('http-assert')
  const UserInfo = require('../../models/UserInfo')
  //const ok = require('assert')
  const User = require('../../models/AdminUser')
  const router = express.Router({
    mergeParams:true
  })
  //const Category = require('../../models/Category')
  //创建分类
  router.post('/',async(req,res)=>{
    
    if (req.Model.modelName === 'AdminUser') {
    //console.log(req.body.username);
      await UserInfo.create({
        username:req.body.username
      })
    }
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  //修改分类
  router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })
  //查询分类
  router.get('/',async(req,res)=>{
    const queryOptions={}
    if (req.Model.modelName==='Category') {
      queryOptions.populate = 'parent'// || 'articles'
    }
    if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories'
    }
    if (req.Model.modelName === 'Video') {
      queryOptions.populate = 'categories'
    }
    console.log(req.Model)
    //const list = await req.Model.find().populate('parent').limit(10)
    const list = await req.Model.find().setOptions(queryOptions)//.limit(100)
    res.send(list)
  })
  //查询10个
  router.get('/pageIndex',async(req,res)=>{
    const {pageSize,pageIndex}=req.query
    if (req.Model.modelName === 'Hero' || req.Model.modelName === 'Article') {
      queryOptions = 'categories'
      const list = await req.Model.find().populate(queryOptions).skip((pageIndex - 1) * pageSize).limit(Number(pageSize))
      res.send(list)
    }else{
      const list = await req.Model.find().skip((pageIndex - 1) * pageSize).limit(Number(pageSize))
      res.send(list)
    }
  })
  //查询详情
  router.get('/:id', async (req, res) => {
    const list = await req.Model.findById(req.params.id)
    res.send(list)
  })
  //删除分类
  router.delete('/:id', async (req, res) => {
    const list = await req.Model.findByIdAndDelete(req.params.id, req.body)
    res.send(list)
  })
  //登录校验中间件
  const authMiddleware = async (req, res, next) => {
    const token = String(req.headers.authorization || "").split(' ').pop();
    if (!token) {
      return res.status(401).send({
        message: '没有jwt token'
      })
    }
    //assert(token,401,'请提供jwt token')
    const {
      id
    } = jwt.verify(token, app.get('secret')) //校验
    //assert(id, 401, '请先登录')
    req.user = await User.findById(id)
    //console.log(user);
    //assert(req.user,401,'请先登录')
    next()
  }
  //resource中间件
  const resourceMiddleware=async(req,res,next)=>{
    const modelName = require('inflection').classify(req.params.resource)//categories=>Category
    req.Model = require(`../../models/${modelName}`)
    await next()
  }
  //封装crud
  app.use('/admin/api/rest/:resource',authMiddleware, resourceMiddleware, router)
  //图片处理
  const multer = require('multer')
  const MAO = require('multer-aliyun-oss');
  const upload = multer({
    storage: MAO({
      config: {
        region: 'oss-cn-chengdu',
        accessKeyId: 'LTAI4FoQAoE3UgbVFV6nS7ke',
        accessKeySecret: 'lmRviETFEMq3TE0jBqIs7htCCRFe3c',
        bucket: 'kings-wzry'
      }
    })
  });
  //const upload = multer({dest:__dirname+'/../../uploads'})//处理文件上传
  app.post('/admin/api/upload',authMiddleware,upload.single('file'),async(req,res)=>{
    const file = req.file
    //file.url = `http://localhost:3001/uploads/${file.filename}`
    //file.url = `http://129.226.50.30/uploads/${file.filename}`
    res.send(file)
  })
  //登录
  app.post('/admin/api/login',async(req, res) => {
    const {username,password} = req.body
    //根据用户名找用户
    const user = await User.findOne({username}).select('+password')//获取密码
    //assert(user, 422, '用户名不存在')//user不存在返回422...
    
    if (!user) {
      return res.status(422).send({
        message:'用户名不存在'
      })
    }
    //校验密码
    const isValid = require('bcryptjs').compareSync(password,user.password)
    //assert(isValid,422,'密码错误')
    if (!isValid) {//❌
      return res.status(422).send({
        message:'用户名或密码错误'
      })
    }
    //返回token
    const token = jwt.sign({
      id:user._id
    },app.get('secret'))//包含id的token
    //返回用户信息
    let user1 = await UserInfo.findOne({username:username})
    user1.token=token
    let users = await UserInfo.findByIdAndUpdate(user1._id,user1)
    //console.log(users);
    //let userinfo = await UserInfo.find().lean()
    return res.send(user1)//({token})//res.send(token)
    //res.send('3333')
  })
  //初始化用户信息
  app.get('/admin/api/userinfo/init',async(req,res)=>{
    const userinfo =  await User.find().lean()
    await userinfo.map(item=>{
      UserInfo.create({
        username:item.username
      })
    })
    res.send(userinfo)
  })
  //错误处理函数
  /* app.use(async(err,req,res,next)=>{
    console.log(err);
    
    res.status(err.status||500).send({
      message:err.message
    })
    //next()
  }) */
}